<template>
  <!--    顶部工具栏-->

  <!--数据展示列表-->
  <div>
    <el-table
      :data="list"
      border
      ref="dragTable"
      row-key="id"
      show-header
      style="width: 100%"

    >

      <!--      <el-table-column type="selection" min-width="2%"></el-table-column>-->

      <el-table-column
        label="id"
        min-width="2%"
        align="center">
        <template slot-scope="scope">
          <span>{{ scope.$index+1}}</span>
          <!--          <span style="margin-left: 0px">{{ scope.row.id}}</span>-->
        </template>
      </el-table-column>
      <el-table-column
        label="活动ID"
        min-width="4%"
        align="center">
        <template slot-scope="scope">
          <span style="margin-left: 0px">{{ scope.row.actid}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="图片名称"
        min-width="4%"
        align="center">
        <template slot-scope="scope">
          <!--          <span style="margin-left: 0px">{{ scope.row.stime }}</span>-->
          <!--          <span style="margin-left: 0px">{{ scope.row.playtime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
          <span style="margin-left: 0px">{{ scope.row.name}}</span>

        </template>
      </el-table-column>
      <el-table-column
        label="image name"
        min-width="4%"
        align="center">
        <template slot-scope="scope">
          <!--          <span style="margin-left: 0px">{{ scope.row.stime }}</span>-->
          <!--          <span style="margin-left: 0px">{{ scope.row.playtime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
          <span style="margin-left: 0px">{{ scope.row.codename_sham}}</span>

        </template>
      </el-table-column>
      <el-table-column
        label="图片"
        min-width="10%"
        align="center">
        <template slot-scope="scope">
          <el-popover placement="right" title="" trigger="hover">
            <img :src="scope.row.url" style="width: 500px;height: 400px"/>

            <img slot="reference" :src="scope.row.url" :alt="scope.row.url" class="img_preview">


            <!--            <div >-->
            <img slot="reference" v-show="checkIsShow(scope.row)" :src="scope.row.tempUrl" :alt="scope.row.tempUrl"
                 class="img_preview" style=" border: 2px dashed #bfcbd9">
            <!--              <span><i classmgt="el-icon-delete" @click="" /></span>-->
            <!--            </div>-->

          </el-popover>
          <el-upload
            :action="imgUrl"
            :data="scope.row"
            :on-change="(file,fileList)=>{return handleChange(file,fileList,scope.row)}"
            :before-upload="handleBeforeUpload"
            :on-success="(response,file,fileList)=>{return handleSuccess(response, file, fileList,scope.row)}"
            :auto-upload=false
            :show-file-list="false"
            :disabled="scope.row.tempUrl.length>0"
            ref="upload"
          >

            <!--            添加图片按钮-->
            <el-button size="mini" type="primary" icon="el-icon-plus" slot="trigger" circle
                       @click="pickImg(scope.row)"></el-button>
            <!--            删除图片按钮-->
            <el-button v-if="checkIsShow(scope.row)" size="mini"
                       icon="el-icon-delete"
                       type="danger" @click="handleRemove(scope.$index, scope.row)" circle></el-button>
            <!--            <div slot="tip" classmgt="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
            <!--            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
          </el-upload>
        </template>


      </el-table-column>

      <el-table-column
        label="修改时间"
        min-width="4%"
        align="center">
        <template slot-scope="scope">
          <span style="margin-left: 0px">{{ scope.row.modifytime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="作者"
        min-width="2%"
        align="center">
        <template slot-scope="scope">
          <span style="margin-left: 0px">{{ scope.row.auther }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center" width="230" class-name="small-padding fixed-width"
        min-width="10%">
        <template slot-scope="scope">

          <el-button-group>
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row)">编辑
            </el-button>
            <el-button size="mini" type="primary" @click="handleSaveImg(scope.row)">保存
            </el-button>

            <el-popover
              placement="top"
              v-model="scope.row.visible"
              icon="el-icon-info"
              iconColor="red"
              title="确定要删除这条数据吗？"

            >
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="scope.row.visible = false">取消</el-button>
                <el-button type="primary" size="mini" @click="handleDelete(scope.$index, scope.row)">确定</el-button>
              </div>
              <el-button slot="reference" size="mini" type="danger">删除</el-button>

            </el-popover>
          </el-button-group>
        </template>
      </el-table-column>

    </el-table>
    <el-button type="primary" size="mini" style="float: left;margin-top: 5px" icon="el-icon-document" @click="handleUploadExcel">题库</el-button>
    <el-button type="" size="mini" style="float: right;margin: 5px" icon="el-icon-plus"
               @click="handleCreate"></el-button>
    <el-button type="danger" size="mini" style="float: right;margin: 5px" icon="el-icon-delete"
               @click="handleDelTabpane"></el-button>

    <!--新增图片面板-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="templist" label-position="left" label-width="100px"
               style="width: 400px; margin-left:50px;">
        <el-form-item label="活动ID" prop="actid">
          <el-input v-model="templist.actid"/>
        </el-form-item>
        <el-form-item label="图片名称" prop="name">
          <el-input v-model="templist.name"/>
        </el-form-item>
        <el-form-item label="image code" prop="codename_sham">
          <el-input v-model="templist.codename_sham"/>
        </el-form-item>

        <!--        <el-form-item label="Remark">-->
        <!--          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea"-->
        <!--                    placeholder="Please input"/>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?diaCreateData():diaUpdateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!--    题库数据面板-->
    <el-dialog title="题库" :visible.sync="dialogTiKuVisible" width="80%" :modal="true">
      <upload-excel-component style="text-align: center" :tape-data="tapeDateExcel" :on-change="handleSuccessExcel"  />

      <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
        <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item"/>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
  import { update, create,downloadAsUrl,deleteImg} from '@/api/act_dati'
  import { isInteger, isPassword } from '@/utils/validate'
  import { isEmpty, parseTime } from '@/utils'
  import noImg from '@/assets/cms_act/img.png'
  import UploadExcelComponent from '@/components/UploadExcel/index.vue'
  import uploadfile from '@/views/klmb/activity/components/uploadfile'

  import { fetchListProgram } from '@/api/article'
  import XLSX from 'xlsx'

  // const PT_TYPE = [
  //   { id: 0, name: 'yd', display_name: '移动' },
  //   { id: 1, name: 'dx', display_name: '电信' },
  //   { id: 2, name: 'lt', display_name: '联通' }
  // ]
  export default {
    props: {
      tabPaneType: {
        type: String,
        default: '1001'
      },
      platformKey: {
        type: Number,
        default: 1
      },
      list: '',
      pt_type: ''

    },
    // components:{uploadfile},
    components:{UploadExcelComponent},
    data() {
      return {

        //---系统变量----

        // imgPath: 'https://wpimg.wallstcn.com/4c69009c-0fd4-4153-b112-6cb53d1cf943',
        // imgPath: 'http://localhost:8180/act/addProduct',
        imgPath:this.$global.VUE_APP_BASE_API_STB+'act/addProduct',

        textMap: [
          'create',
          'edit'
        ],
        dialogStatus: 0,
        dialogFormVisible: false,

        //题库数据
        dialogTiKuVisible:false,
        tableData: [],
        tableHeader: [],
        // tapeDateExcel:{},
        tapeDateExcel:{//上传excel时用到的部分参数
          actid:this.tabPaneType,
          name:"题库",//固定名称
          codename:"qusbank_"+this.tabPaneType,//固定名称
          codename_sham:"qusbank",
          url:this.pt_type.server,             //此项为空
          auther:"cxy",
          excelurl:this.pt_type.server,        //excel保存的路径
          modifytime:parseTime(new Date()),
          platform:this.platformKey
        },

        // list: this.listdata,
        templist: {
          id:'',
          actid: '1001',
          name: '测试',
          codename: 'homebg',
          codename_sham:'',
          modifytime: '2020-10-14 09:52:23',
          visible: false,
          url: 'https://wpimg.wallstcn.com/4c69009c-0fd4-4153-b112-6cb53d1cf943',
          auther: 'cxy',
          tempUrl: '',
          excelurl:'',
          tempImgUpload: false
        },
        //编辑面板操作的数据对象基础模数据
        templistTape: {
          id: '',
          actid: this.tabPaneType,
          name: '',
          codename: '',
          codename_sham:'',
          modifytime: '',
          visible: false,
          url: noImg,
          auther: 'admin',
          tempUrl: '',
          excelurl:'',
          tempImgUpload: false, //临时图片是否转正（O(∩_∩)O哈哈~）
          platform: this.platformKey
        },
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,

        rules: {
          actid: [{ required: true, message: '必须是数字', trigger: 'blur' }, { validator: this.rules_CheckIsActid||isInteger, trigger: 'blur' }],
          codename_sham: [{ required: true, message: '字母/数字/下划线且非数字开头/重名', trigger: 'blur' }, { validator: this.rules_CheckIsDuplicate||isPassword,  trigger: 'blur'  }]
        }
      }
    },
    created() {

    },
    watch: {

      list() {
        let pt_type_server = this.pt_type.server
        this.list.forEach((ele, index)=> {
          if(ele.codename_sham=="qusbank"){
            if(isEmpty(ele.excelurl)){
              ele.url = pt_type_server
              ele.excelurl = pt_type_server
            }
            this.tapeDateExcel =  Object.assign({}, ele)
            this.list.splice(index,1)//删除是为了不让excel文件显示在活动图片展示列表内
          }else{
            if (ele.url == null || ele.url.length == 0) {
              ele.url = noImg
            }
          }

        })
      }

    },
    computed: {
      imgUrl() {
        return this.$global.VUE_APP_BASE_API_STB+'act/addProduct'
      },

    },
    methods: {
      // =======================上传Excel=======================

      // onTableData(td){
      //   this.tableData = td;
      //   console.log("父组件接收值："+td)
      // },
      handleSuccessExcel({ results, header }) {
        console.log('上传Excel')
        this.tableData = results
        this.tableHeader = header
      },
      handleUploadExcel(){
        this.dialogTiKuVisible = true;
        // this.getServerExcel();
        console.log("题库："+JSON.stringify(this.tapeDateExcel))

      },


      getServerExcel(){
        let url = "http://localhost:8180/cms_act_data/1001/abc.xlsx"
        // let url = "http://localhost:8180/cms_act_data/1001/home.png"

        downloadAsUrl(url,"blob",{filename:"abc"})
          .then(
          (response)=>{
            console.log("getServerExcel:response=="+response)

            let reader = new FileReader();
            reader.readAsText(new Blob(response.data));
            reader.onload = e => {
              const data = e.target.result
              const workbook = XLSX.read(data, { type: 'array' })
              const firstSheetName = workbook.SheetNames[0]
              const worksheet = workbook.Sheets[firstSheetName]
              const header = this.getHeaderRow(worksheet)
              const results = XLSX.utils.sheet_to_json(worksheet)
              // this.generateData({ header, results })
              this.tableData = results
              this.tableHeader = header
              this.loading = false
            }
          }
        )
        // .catch(er=>{
        //
        //   console.log("getServerExcel:error=="+JSON.stringify(er))
        // })




      },

      // beforeUploadExcel(file) {
      //   const isLt1M = file.size / 1024 / 1024 < 1
      //
      //   if (isLt1M) {
      //     return true
      //   }
      //
      //   this.$message({
      //     message: 'Please do not upload files larger than 1m in size.',
      //     type: 'warning'
      //   })
      //   return false
      // },
      // handleSuccessExcel({ results, header }) {
      //   console.log("上传Excel")
      //   this.tableData = results
      //   this.tableHeader = header
      // },


      rules_CheckIsDuplicate(rule, value, callback) {
        for (let i = 0; i < this.list.length; i++) {
          if(this.list[i].id!=this.templist.id){
            if(this.list[i].codename_sham == value){
              return callback(JSON.stringify(value)+"名称已存在重名")
            }
          }

        }
        return callback()
      },

      rules_CheckIsActid(rule, value, callback){
        console.log("rules_CheckIsActic="+value+" ： "+this.tabPaneType)
        if(value!=this.tabPaneType){
          return callback("活动ID不符")
        }else{ return callback()}

      },

      checkIsShow(row) {
        // console.log("tempUrl.length:"+row.tempUrl.length+" tempUrl:"+row.tempUrl+" url:"+row.url)

        return row.tempUrl.length > 0 && row.tempUrl != row.url

      },
      pickImg(row) {
        console.log(' row.tempUrl=' + row.tempUrl)

        if (row.tempUrl.length > 0) {

        } else {
          row.tempImgUpload = false
        }

      },

      submitUpload() {
        this.$refs.upload.submit()
      },

      changePlatform(label) {
        this.platformKey = label
      },

      handleUpdate(file) {

      },
      handleRemove(index, row) {
        // console.log(file.url)
        // console.log(JSON.stringify(file))
        // file = ''
        // this.$emit('input', '')
        // this.disabled = true
        row.tempUrl = ''
        row.tempImgUpload = false
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },

      handleDownload(file) {
        console.log('下载功能暂未开放')
      },

      handleDelete(index, row) {

        console.log("handleDelete")
        // deleteImg(this.list[index]).then((response) => {
        deleteImg(row).then((response) => {
          row.visible = false;
          if(response.code==20000){
            this.$notify({
              title: 'Success',
              message: 'Delete Successfully',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          }else{
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          }

        })


      },

      handleChange(file, fileList, row) {
        // console.log(JSON.stringify(row))
        // console.log(JSON.stringify(file))

        if (row.tempImgUpload) {
          row.tempUrl = ''
        } else {
          row.tempUrl = URL.createObjectURL(file.raw)
          row.tempImgUpload = false
        }
        // row.url = URL.createObjectURL(file.raw);

      },

      handlePreview(file, row) {
        // row.tempUrl = URL.createObjectURL(file.raw)

      },
      handleBeforeUpload(file) {
        // console.log(JSON.stringify(file))
      },
      /**
       *
       * 新增数据
       */
      handleCreate() {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true

        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          this.$refs['dragTable'].doLayout()
          // console.log("2$refs="+this.$refs.dragTable)
        })

        this.resetTemp();

      },

      handleDelTabpane() {
        this.$notify({
          title: 'Warning',
          message: '刪除面板功能暂不开放',
          type: 'warning',
          duration: 1000
        })
      },

      handleSuccess(response, file, fileList, row) {
        // row.url = response.toString()+"?tm="+new Date();//加个时间戳，及时刷新图片
        row.url = response.toString();//加个时间戳，及时刷新图片
        console.log('handleSuccess=' + row.url)

        row.tempImgUpload = true

      },

      /**
       *
       * 编辑数据
       */
      handleEdit(row) {
        this.dialogStatus = 'edit'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        // this.templist = Object.assign({}, row)
        this.templist = row

        console.log("编辑数据："+JSON.stringify(this.templist))

      },

      /***
       *
       * 仅保存图片
       * @param row
       */
      handleSaveImg(row) {
        if (row.tempUrl.length > 0) {
          // row.url = row.tempUrl+""
          row.url = this.pt_type.server
          // console.log('1保存图片:' + this.imgUrl)

          console.log('1保存图片:' + JSON.stringify(row))
          this.$refs.upload.submit()
          console.log('2保存图片:' + JSON.stringify(row))

        } else {
          this.$notify({
            title: '警告',
            message: '图片无数据',
            type: 'warning',
            duration: 1000
          })
        }
      },

      resetTemp() {
        this.templist = Object.assign({}, this.templistTape)
      },

      async diaCreateData() {
        this.dialogFormVisible = false
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.templist.modifytime = parseTime(new Date())
            // this.templist.id = parseInt(Math.random() * 100) + 1024 // mock a id
            // this.templist.url = this.noImg
            this.templist.url = ''
            this.templist.codename = (this.templist.codename_sham+"_"+this.templist.actid)
            console.log("插入数据到数据库:"+JSON.stringify(this.templist))
            //todo 插入数据到数据库
            create(this.templist).then((response) => {
              this.templist.id = response.data
              this.templist.url = noImg
              console.log('handleCreate:' + response.msg)
              console.log('handleCreate:' + response.data)
              this.list.push(this.templist)
            })
          } else {
            this.$notify({
              title: '失败',
              message: '参数不合法',
              type: 'error',
              duration: 1000
            })
          }

        })

      },
      diaUpdateData() {
        this.dialogFormVisible = false
        // row = Object.assign({}, this.templist)
        // const index = this.list.findIndex(v => v.id === this.templist.id)
        // this.list[index] = this.templist

        console.log(JSON.stringify(this.templist))
        //todo 更新数据到数据库

        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.templist.modifytime = parseTime(new Date())
            // this.templist.id = parseInt(Math.random() * 100) + 1024 // mock a id
            // this.templist.url = this.noImg
            // this.templist.url = ''
            console.log(JSON.stringify(this.templist))
            this.templist.codename = (this.templist.codename_sham+"_"+this.templist.actid)

            //todo 插入数据到数据库
            update(this.templist).then((response) => {
              this.templist.url = response.data.url
              console.log('diaUpdateData:' +response.data)
              //这里需要将修改后的数据刷新到list中


            })
          } else {
            this.$notify({
              title: '失败',
              message: '参数不合法',
              type: 'error',
              duration: 1000
            })
          }

        })




      },



    }
  }
</script>

<style scoped>
  el-table-column {
    max-height: 10%;
  }

  .line {
    text-align: center
  }

  .upload-demo {
    display: inline;
  }

  .img_preview {
    /*max-height: 50px;max-width: 130px;*/
    max-height: 10%;
    max-width: 20%;
    margin-left: 10px;
    /*background-color: #42b983;*/
  }

  .img_temp_preview {
    width: 50px;
    height: 50px;
    /*float: left;*/

    /*max-height: 15%;*/
    /*max-width: 30%;*/
    /*position: relative;*/
    border: 1px dashed #d9d9d9;
    /*display: block;*/
  }
</style>

